'use strict';
const uniID = require('uni-id-common')
exports.main = async (event, context) => {
	const uniIDIns = uniID.createInstance({
		context: context,
	})
	const db = uniCloud.databaseForJQL({
		event,
		context
	});
	var templist = []
	var tempurl = []
	async function bl(data) {
		for (var i in data) {
			templist.push(data[i]._id)
			tempurl.push({
				url: data[i].url,
				icon: data[i].icon
			})
			const id = await db.collection('item').where({
				up: data[i]._id,
				user_id: res.uid
			}).get()
			if (id.data.length > 0) {
				await bl(id.data)
			} else {
				continue;
			}
		}
	}
	const res = await uniIDIns.checkToken(event.uniIdToken)
	if (event.id == null) {
		return null
	}
	const deleid = await db.collection('item').where({
		up: event.id,
		user_id: res.uid
	}).get()
	templist.push(event.id)
	await db.collection('link').where({
		item_id: event.id,
		user_id: res.uid
	}).remove()
	await bl(deleid.data)
	for (var i in templist) {
		await db.collection('item').where({
			_id: templist[i],
			user_id: res.uid
		}).remove()
		await db.collection('link').where({
			item_id: templist[i],
			user_id: res.uid
		}).remove()
		await db.collection('comment').where({
			item_id: templist[i]
		}).remove()
		await db.collection('good').where({
			item_id: templist[i]
		}).remove()
		await db.collection('order').where({
			item_id: templist[i]
		}).remove()
		await db.collection('rate').where({
			item_id: templist[i]
		}).remove()
		await db.collection('collect').where({
			item_id: templist[i]
		}).remove()
	}
	for (let item of tempurl) {
		await db.collection("delete_file").add({
			time: new Date().getTime(),
			user_id: res.uid,
			url: item.url,
			icon: item.icon
		});
	}
	return {
		msg: "删除成功"
	}
};